<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Aboot\Attribute;
use App\Model\Admin\Product;
use App\Model\Admin\ProductAttr;
use App\Model\Admin\ProductImage;
use App\Model\Admin\ProductType;
use App\Model\Front\Category;
use App\Services\CategoriesChildService;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::orderBy('id','desc')->get();
        return view('admin.product.index', compact('products'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category::all();
        $types = ProductType::all();
        return view('admin.product.create', compact('categories', 'types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        /**
        * 判断是否有图片上传或者多个图片
        **/
        isset($request->file) ? $file = array_flip(array_flip($request->input('file'))): '';
        $getimageName = '';
        if ($request->file('pro_img')) {
            $image = $request->file('pro_img');
            $getimageName = time().'.'.$request->pro_img->getClientOriginalExtension();
            $request->pro_img->move(public_path('productpics'), $getimageName);
        }

        $pro_code = (int) $request->pro_code;
        //是否自动生成编号
        if ($request->auto) 
        {
            $this->autoMakeCode();
        }
        $promote_status = $request->is_promote;

        if (!$request->is_promote) 
        {
            $promote_status = 0;
        }

        //写入数据库返回id
        $product = Product::insertGetId([
                  'pro_name'=>$request->pro_name,
                  'pro_info'=>$request->pro_info,
                  'pro_img'=>$getimageName,
                  'pro_code'=>$pro_code,
                  'pro_description'=>$request->pro_description,
                  'spl_prices'=>$request->spl_prices,
                  'pro_prices'=>$request->pro_prices,
                  'pro_stock'=>$request->pro_stock,
                  'cate_id'=>$request->cate_id,
                  'is_promote'=>$promote_status,
                  'promote_price'=>$request->promote_price,
                  'promote_start_time'=>strtotime($request->promote_start_time),
                  'promote_end_time'=>strtotime($request->promote_end_time),
                  'is_hot'=>$request->is_hot,
                  'type_id'=>$request->type_id,
                  'is_new'=>$request->is_new,
                  'is_best'=>$request->is_best,
                  'created_at'=>date('Y-m-d H:i:s')
            ]);

        if ($request->type_id) 
        {
            $ga = $request->input('ga');
            $ap = $request->input('attr_price');
            foreach ($ga as $key=>$value1) {
                foreach ($value1 as $k=>$v) 
                {
                    if (empty($v)) 
                    {
                        continue ;
                    } 
                    ProductAttr::create([
                      'product_id'=>$product,
                      'attr_id'=>$key,
                      'attr_value'=>$v,
                      'attr_price'=>@$ap[$key][$k]
                ]);
                }
            }
        }
        //查找最新的一条
        $product = Product::where('id', $product)->first();
        $product->is_floor = $request->is_floor;

        //写入多图
        if (!empty($file)) 
        {
            foreach ($file as $value) 
            {
                ProductImage::create(['product_id'=>$product->pro_code, 'image_path'=>'child_pic/'.$value]);
            }
        }

        if ($product) {
            $this->clearHomeCache();
            $product->save();
            $request->session()->flash('success', '添加成功!');
            return redirect()->route('product.index');
        }
    }


    protected function createUpload()
    {
        if (request()->file('file')) {
            $image = request()->file('file');
            foreach ($image as $k=>$v) {
                foreach ($v as $value) {
                    $number = range(1, 10);
                    shuffle($number);
                    $num=9;
                    $pro_codes = array_slice($number, 0, $num);
                    $pro_code_new = implode(',', $pro_codes);
                    $pro_code = str_replace(',', '', $pro_code_new);
                    $getimageName[] = $pro_code.'pi_'.time().'.'.$value->getClientOriginalExtension();
                    $path = $value->move('child_pic', $getimageName[$k]);
                    // dd($path);
                }
            }
            array_unique($getimageName);
        }
        return $getimageName;
    }

    protected function uploadFile($product_id=null, Product $product=null)
    {
        // var_dump(!empty($product));
        // dd($product->pro_code);
        if (!empty($product)) {
            if (request()->file('file')) {
                $image = request()->file('file');
                foreach ($image as $k=>$v) {
                    $value = Hash::make('dd');

                    $getimageName[] = $value.'pi_'.time().'.'.$v->getClientOriginalExtension();
                    $path = $v->move('child_pic', $getimageName[$k]);
                    ProductImage::create(['product_id'=>$product->pro_code, 'image_path'=>$path]);
                }
            }
           
            return "done";
        }
    }


    protected function autoMakeCode()
    {
      $number = range(1, 10);
      shuffle($number);
      $num=9;
      $pro_codes = array_slice($number, 0, $num);
      $pro_code_new = implode(',', $pro_codes);
      $pro_code = str_replace(',', '', $pro_code_new);
      return $pro_code;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Model\Admin\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        $now = time();
        if($product->promote_end_time < $now){

          $product->is_promote = false;
          $product->save();

        }
        $cates = Category::all();
        $types = ProductType::all();
        $categories = CategoriesChildService::unlimitedForLevel($cates);
        $attributes = ProductAttr::leftJoin('product_attributes AS pa', 'product_attrs.attr_id', 'pa.id')
                                  ->where('product_id', $product->id)
                                  ->select(
                                      'pa.id AS pid',
                                       'pa.type_id',
                                       'pa.attr_name',
                                       'pa.attr_type',
                                       'pa.attr_option_values',
                                       'product_attrs.*'
                                  )
                                  ->orderBy('product_attrs.attr_id', 'asc')
                                  ->get();

        //判断有没有新属性,
        $attr_id = [];
        foreach ($attributes as $value) {
            $attr_id[] = $value->attr_id;
        }
        $attr_id = array_unique($attr_id);
        $otherAttrs = Attribute::whereNotIn('id', $attr_id)
                                 ->select(
                                    'id AS attr_id', 
                                    'type_id', 
                                    'attr_name', 
                                    'attr_type', 
                                    'attr_option_values')
                                 ->where('type_id', $product->type_id)
                                 ->get();
        $attributes = array_merge($attributes->toArray(), $otherAttrs->toArray());
        // dd($attributes);

        return view('admin.product.edit', compact('categories', 'attributes', 'new', 'product', 'types'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Model\Admin\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        // dd($request->input());
        $pro_code = (int) $request->pro_code;
        $getimageName = $product->pro_img;


        if ($request->file('pro_img')) {
            File::delete('productpics/'.$product->pro_img);
            $image = $request->file('pro_img');
            $getimageName = time().'.'.$request->pro_img->getClientOriginalExtension();
            $request->pro_img->move(public_path('productpics'), $getimageName);
        }
        if ($request->auto) {
            $number = range(1, 10);
            shuffle($number);
            $num=9;
            $pro_codes = array_slice($number, 0, $num);
            $pro_code_new = implode(',', $pro_codes);
            $pro_code = str_replace(',', '', $pro_code_new);
        }
        
        $promote_status = $request->is_promote;
        if (!$request->is_promote) {
            $promote_status = 0;
        }
        /***是否有改动类型id***/
        if ($product->type_id != $request->type_id) {
            ProductAttr::where('product_id', $product->id)
                       ->delete();
        }
        $product->update([
                  'pro_name'=>$request->pro_name,
                  'pro_info'=>$request->pro_info,
                  'pro_img'=>$getimageName,
                  'pro_code'=>$pro_code,
                  'pro_description'=>$request->pro_description,
                  'spl_prices'=>$request->spl_prices,
                  'pro_prices'=>$request->pro_prices,
                  'cate_id'=>$request->cate_id,
                  'is_promote'=>$promote_status,
                  'promote_price'=>$request->promote_price,
                 'promote_start_time'=>strtotime($request->promote_start_time),
                  'promote_end_time'=>strtotime($request->promote_end_time),
                  'is_hot'=>$request->is_hot,
                  'type_id'=>$request->type_id,
                  'is_new'=>$request->is_new,
                  'is_best'=>$request->is_best,
                  'is_floor'=>$request->is_floor

            ]);
        //###############修改商品属性###############//
        //1,添加新属性
        if ($request->type_id) {
          // dd($request->input());
            $ga = $request->input('ga');
            $ap = $request->input('attr_price');
            if($ga){
              foreach ($ga as $key=>$value1) {
                foreach ($value1 as $k=>$v) {
                    if (empty($v)) {
                        continue ;
                    } else {
                        ProductAttr::create([
                            'product_id'=>$product->id,
                            'attr_id'=>$key,
                            'attr_value'=>@$v,
                            'attr_price'=>@$ap[$key][$k]
                      ]);
                    }
                }
            }
            }
        }
        //2处理原属性
        $old_ga = $request->input('old_ga');
        $old_ap = $request->input('old_attr_price');
        if ($old_ga||$old_ap) {
            //更新原属性
            foreach ($old_ga as $k=>$v) {
                foreach ($v as $k1=>$v1) {
                    // dump($old_ap);

                    if (empty($v)) 
                    {
                        continue ;
                    } else 
                    {
                        ProductAttr::where('product_id', $product->id)->where('id', $k1)->update(['attr_value'=>$v1,'attr_price'=>@$old_ap[$k][$k1]]);
                    }
                }
            }
        }
        $this->clearHomeCache();
        return redirect()->route('product.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Model\Admin\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        File::delete('productpics/'.$product->pro_img);

        $product->delete();
        $product->images()->delete();
        $this->clearHomeCache();

        return back();
    }

    
}
